<template>
  <div class="room-page-wrapper">
    <div class="room-status-container" style="background-color: transparent;">
      <!-- 查询与筛选表单 -->
      <div class="search-bar" id="box">
        <h2 class="search-title">会议室预约</h2>
        <p class="search-guide">您可以通过名称、类型和状态筛选会议室，点击会议室卡片查看详情</p>
        <form class="search-form" @submit.prevent="handleSearch">
          <div class="form-group">
            <label for="room-name">会议室名称</label>
            <input 
              type="text" 
              id="room-name" 
              v-model="searchForm.name" 
              placeholder="请输入会议室名称"
              class="custom-input"
            >
          </div>
          
          <div class="form-group">
            <label for="room-type">会议室类型</label>
            <select 
              id="room-type" 
              v-model="searchForm.type" 
              class="custom-select"
            >
              <option value="" selected>全部类型</option>
              <option :value="0">教室型</option>
              <option :value="1">圆桌型</option>
            </select>
          </div>    
          
          <div class="form-actions">
            <button type="submit" class="btn btn-primary">查询</button>
            <button type="button" class="btn btn-secondary" @click="resetSearch">刷新</button>
            <button type="button" class="btn btn-primary" @click="handleRecommend">快速推荐</button>
          </div>
        </form>
      </div>
      <!-- 推荐条件展示 -->
      <div v-if="showRecommendInfo" class="recommend-info">
        <el-alert
          title="推荐条件（价格由低到高排序）"
          type="info"
          :closable="false"
          style="width: auto; text-align: center; border-radius: 14px;"
        >
          <template #default>
            <div class="recommend-criteria" style="display: flex; flex-wrap: wrap; justify-content: center; gap: 8px;">
              <span class="criteria-item">时间范围：{{ formatTimeRange(recommendTimeRange) }}</span>
              <span class="criteria-item">参会人数：{{ recommendAttendees }}人</span>
              <span v-if="recommendDevices.length" class="criteria-item">所需设备：{{ recommendDevices.join(', ') }}</span>
              <span v-if="recommendMaxPrice" class="criteria-item">最高价格：{{ recommendMaxPrice }}元/时</span>
              <span v-if="recommendType !== null" class="criteria-item">会议室类型：{{ recommendType === 0? '教室型' : recommendType === 1? '圆桌型' : '' }}</span>
            </div>
          </template>
        </el-alert>
      </div>
      
      <!-- 会议室列表 -->
      <div class="room-grid-container">
        <div class="room-grid">
          <div v-for="room in roomList" :key="room.id" class="room-card" @click="handleRoomClick(room)">
            <div class="room-card-header">
              <span class="room-name">{{ room.name }}</span>
              <span class="room-status">
                <el-tag :type="getStatusTagType(room.curStatus)">
                  {{ getStatusText(room.curStatus) }}
                </el-tag>
              </span>
            </div>
            <div class="room-card-type">
              {{ room.type === 0 ? '教室型' : room.type === 1 ? '圆桌型' : '' }}
            </div>
            <img 
              v-if="room.type === 1 && room.seatNum <= 6"
              src="../../assets/pic/TableRoom_Regular.png" 
              class="room-decoration-TableRoom-Regular"
              alt="小型圆桌装饰"
            />
            <img 
              v-if="room.type === 1 && room.seatNum > 6"
              src="../../assets/pic/TableRoom_Big.png" 
              class="room-decoration-TableRoom"
              alt="大型圆桌装饰"
            />
            <img 
              v-if="room.type === 0 && room.seatNum <= 6"
              src="../../assets/pic/ClassRoom_Regular.png" 
              class="room-decoration-ClassRoom-Regular"
              alt="小型教室装饰"
            />
            <img 
              v-if="room.type === 0 && room.seatNum > 6"
              src="../../assets/pic/ClassRoom_Big.png" 
              class="room-decoration-ClassRoom"
              alt="大型教室装饰"
            />
          </div>
        </div>
      </div>

    <!-- 会议室详情对话框 -->
    <div v-if="roomDetailVisible" class="room-detail-dialog">
      <div class="dialog-content">
        <div class="dialog-header">
          <h2>会议室详情</h2>
          <el-button class="close-btn" @click="roomDetailVisible = false" :icon="Close" circle />
        </div>
        <div class="dialog-body">
          <div class="room-image-container">
            <div v-if="currentRoom.type === 1 && currentRoom.seatNum <= 6" class="room-detail-model">
              <div class="loading-spinner" v-if="isLoadingModel">
                <div class="spinner"></div>
                <span class="loading-text">加载中...</span>
              </div>
              <spline-viewer 
                :url="MODEL_URLS.smallTable"
                :preload="true"
                @load="isLoadingModel = false"
              ></spline-viewer>
            </div>
            <div v-if="currentRoom.type === 1 && currentRoom.seatNum > 6" class="room-detail-model">
              <div class="loading-spinner" v-if="isLoadingModel">
                <div class="spinner"></div>
                <span class="loading-text">加载中...</span>
              </div>
              <spline-viewer 
                :url="MODEL_URLS.bigTable"
                :preload="true"
                @load="isLoadingModel = false"
              ></spline-viewer>
            </div>
            <div v-if="currentRoom.type === 0 && currentRoom.seatNum <= 6" class="room-detail-model">
              <div class="loading-spinner" v-if="isLoadingModel">
                <div class="spinner"></div>
                <span class="loading-text">加载中...</span>
              </div>
              <spline-viewer 
                :url="MODEL_URLS.smallClass"
                :preload="true"
                @load="isLoadingModel = false"
              ></spline-viewer>
            </div>
            <div v-if="currentRoom.type === 0 && currentRoom.seatNum > 6" class="room-detail-model">
              <div class="loading-spinner" v-if="isLoadingModel">
                <div class="spinner"></div>
                <span class="loading-text">加载中...</span>
              </div>
              <spline-viewer 
                :url="MODEL_URLS.bigClass"
                :preload="true"
                @load="isLoadingModel = false"
              ></spline-viewer>
            </div>
          </div>
          <div class="room-detail">
            <div class="detail-item">
              <span class="label">会议室名称：</span>
              <span class="value">{{ currentRoom.name }}</span>
            </div>
            <div class="detail-item">
              <span class="label">类型：</span>
              <span class="value">{{ currentRoom.type === 0 ? '教室型' : currentRoom.type === 1 ? '圆桌型' : '' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">面积：</span>
              <span class="value">{{ currentRoom.area }} 平方米</span>
            </div>
            <div class="detail-item">
              <span class="label">座位数：</span>
              <span class="value">{{ currentRoom.seatNum }} 个</span>
            </div>
            <div class="detail-item">
              <span class="label">价格：</span>
              <span class="value price">{{ currentRoom.price }} 元/小时</span>
            </div>
            <div class="detail-item">
              <span class="label">当前状态：</span>
              <span class="status-tag" :class="getStatusClass(currentRoom.curStatus)">
                {{ getStatusText(currentRoom.curStatus) }}
              </span>
            </div>
            <div class="detail-item">
              <span class="label">查看会议室状态：</span>
              <el-date-picker
                v-model="selectedDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                :disabled-date="(time) => time.getTime() < Date.now() - 86400000"
                @change="fetchRoomStatus"
                style="width: 140px"
              />
            </div>
            <div class="detail-item" v-if="roomStatusString">
              <div class="status-legend">
                <div class="legend-title">状态说明</div>
                <div class="legend-items">
                  <div class="legend-item">
                    <div class="legend-color" style="background-color: #67c23a;"></div>
                    <span class="legend-text">空闲</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color" style="background-color: #e6a23c;"></div>
                    <span class="legend-text">锁定</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color" style="background-color: #409eff;"></div>
                    <span class="legend-text">预定</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color" style="background-color: #f56c6c;"></div>
                    <span class="legend-text">使用</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color" style="background-color: #909399;"></div>
                    <span class="legend-text">维护</span>
                  </div>
                </div>
              </div>
              <div class="time-status-grid">
                <div v-for="(status, index) in roomStatusArray" :key="index" class="time-status-item">
                  <span class="time-label" :class="getStatusClass(Number(status))">
                    {{ index.toString().padStart(2, '0') }}:00 - {{ (index + 1).toString().padStart(2, '0') }}:00
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="detail-actions">
          <button class="action-btn view-devices" @click="handleViewDevices(currentRoom)">查看设备</button>
          <button class="action-btn book-room" @click="handleBookRoom(currentRoom)">预约</button>
        </div>
      </div>
    </div>

    <!-- 设备列表对话框 -->
    <el-dialog
        title="设备列表"
        v-model="deviceDialogVisible"
        width="30%"
      >
        <el-table :data="currentRoomDevices" border style="width: 100%">
          <el-table-column prop="name" label="设备名称"></el-table-column>
          <el-table-column prop="description" label="设备描述"></el-table-column>
        </el-table>
      </el-dialog>

    <!-- 预约对话框 -->
    <el-dialog title="预约会议室" v-model="bookingDialogVisible" width="30%">
      <el-form :model="bookingForm" ref="bookingFormRef" :rules="bookingRules">
        <el-form-item label="预约日期" prop="date" :rules="[{ required: true, message: '请选择预约日期', trigger: 'change' }]">
          <el-date-picker v-model="bookingForm.date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" :disabledDate="(time) => time.getTime() < Date.now()" style="width: 100%" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime" :rules="[{ required: true, message: '请选择开始时间', trigger: 'change' }]">
          <el-time-picker v-model="bookingForm.startTime" placeholder="开始时间" format="HH:00" value-format="HH:00" :step="'60'" style="width: 100%" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime" :rules="[{ required: true, message: '请选择结束时间', trigger: 'change' }]">
          <el-time-picker v-model="bookingForm.endTime" placeholder="结束时间" format="HH:00" value-format="HH:00" :step="'60'" style="width: 100%" />
        </el-form-item>
        <el-form-item label="参会人数" prop="attendees" :rules="[{ required: true, message: '请输入参会人数', trigger: ['change', 'blur'] }, { validator: validateAttendees, trigger: ['change', 'blur'] }]">
          <el-input-number v-model="bookingForm.attendees" :min="1"  :precision="0" :step="1" placeholder="请输入参会人数" style="width: 100%">
            <template #description>
              <span style="color: #909399; font-size: 12px;">最多可容纳 {{ currentRoom.seatNum }} 人</span>
            </template>
          </el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bookingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBooking" :loading="isSubmitting" :disabled="isSubmitting">{{ isSubmitting ? '提交中...' : '提交预约' }}</el-button>
      </template>
    </el-dialog>

    <!-- 快速推荐对话框 -->
    <el-dialog title="快速推荐" v-model="recommendDialogVisible" width="40%">
      <el-form :model="recommendForm" label-width="120px" ref="recommendFormRef" :rules="recommendRules">
        <el-form-item label="预约日期" prop="date" :rules="[{ required: true, message: '请选择预约日期', trigger: 'change' }]">
          <el-date-picker v-model="recommendForm.date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" :disabledDate="(time) => time.getTime() < Date.now()" style="width: 100%" />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-radio-group v-model="timeRangeType" @change="handleTimeRangeChange" style="margin-bottom: 10px;">
            <el-radio-button label="custom">自定义</el-radio-button>
            <el-radio-button label="allDay">全天 (8:00-21:00)</el-radio-button>
            <el-radio-button label="morning">上午 (8:00-12:00)</el-radio-button>
            <el-radio-button label="afternoon">下午 (12:00-18:00)</el-radio-button>
            <el-radio-button label="evening">晚上 (18:00-21:00)</el-radio-button>
          </el-radio-group>
          <div v-if="timeRangeType === 'custom'">
            <el-form-item prop="startTime" :rules="[{ required: true, message: '请选择开始时间', trigger: 'change' }]" style="display: inline-block; width: 48%; margin-right: 4%; margin-bottom: 0;">
              <el-time-picker v-model="recommendForm.startTime" placeholder="开始时间" format="HH:00" value-format="HH:00" :step="'60'" style="width: 100%" />
            </el-form-item>
            <el-form-item prop="endTime" :rules="[{ required: true, message: '请选择结束时间', trigger: 'change' }]" style="display: inline-block; width: 48%; margin-bottom: 0;">
              <el-time-picker v-model="recommendForm.endTime" placeholder="结束时间" format="HH:00" value-format="HH:00" :step="'60'" style="width: 100%" />
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="参会人数" prop="attendees" :rules="[{ required: true, message: '请输入参会人数', trigger: 'change' }]">
          <el-input-number v-model="recommendForm.attendees" :min="1" :precision="0" :step="1" placeholder="请输入参会人数" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="所需设备">
          <el-select v-model="recommendForm.deviceIds" multiple placeholder="请选择所需设备" clearable style="width: 100%">
            <el-option v-for="device in devicesList" :key="device.id" :label="device.name" :value="device.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最高时价">
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input v-model="recommendForm.maxPrice" type="number" placeholder="元/时"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="会议室类型">
          <el-select v-model="recommendForm.type" placeholder="全部类型" clearable style="width: 100%">
            <el-option label="教室型" :value="0"></el-option>
            <el-option label="圆桌型" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitRecommend" :loading="isRecommending" :disabled="isRecommending">{{ isRecommending ? '推荐中...' : '开始推荐' }}</el-button>
      </template>
    </el-dialog>

    <!-- 支付对话框 -->
    <el-dialog title="订单支付" v-model="payDialogVisible" width="30%" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="pay-dialog-content">
        <div class="order-amount">
          <el-alert type="info" :closable="false">
            <template #default>
              <div class="amount-text">
                <span>订单金额：</span>
                <span class="amount-number">¥ {{ orderAmount }}</span>
              </div>
            </template>
          </el-alert>
        </div>
        <div class="countdown-info">
          <el-alert type="warning" :closable="false">
            <template #default>
              <div class="countdown-text">
                <span>请在 </span>
                <span class="countdown-number">{{ formatCountdown(paymentCountdown) }}</span>
                <span> 内完成支付</span>
              </div>
            </template>
          </el-alert>
        </div>
        <div class="payment-method-select">
          <p class="section-title">请选择支付方式：</p>
          <el-radio-group v-model="paymentMethod">
            <el-radio :label="0">支付宝</el-radio>
            <el-radio :label="1">微信</el-radio>
            <el-radio :label="2">银联</el-radio>
          </el-radio-group>
        </div>
        <div v-if="showQRCode" class="qr-code-container" style="text-align: center; margin-top: 20px;">
          <img src="/qr-code.svg" alt="支付二维码" style="width: 200px; height: 200px;">
          <p style="margin-top: 10px; color: #666;">请使用{{ paymentMethod === 0 ? '支付宝' : paymentMethod === 1 ? '微信' : '银联' }}扫码支付</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <template v-if="!showQRCode">
            <el-button @click="handlePayLater">稍后支付</el-button>
            <el-button type="primary" @click="handlePayNow">立即支付</el-button>
          </template>
          <template v-else>
            <el-button @click="cancelPayment">取消支付</el-button>
            <el-button type="primary" @click="confirmPayment" :loading="isPaymentProcessing">{{ isPaymentProcessing ? '处理中...' : '我已完成支付' }}</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import request from '../../api/request'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import timezone from 'dayjs/plugin/timezone'
import { Close } from '@element-plus/icons-vue'
import { BlurGradientBg } from "../../components/BlurGradientBg.module.js"

// 添加插件
dayjs.extend(utc)
dayjs.extend(timezone)

const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

const roomList = ref([])
const devicesList = ref([])
const roomDetailVisible = ref(false)
const deviceDialogVisible = ref(false)
const currentRoom = ref({})
const selectedDate = ref(dayjs().format('YYYY-MM-DD'))
const roomStatusString = ref('')
const roomStatusArray = computed(() => roomStatusString.value.split(''))
const isLoadingModel = ref(true)

const bookingDialogVisible = ref(false)
const bookingFormRef = ref(null)
const bookingForm = reactive({ 
  date: '',
  startTime: '',
  endTime: '',
  attendees: null,
  deviceIds: []
})

const fetchRoomStatus = async () => {
  if (!selectedDate.value || !currentRoom.value.id){
    roomStatusString.value = ''
    return
  }
  const response = await request({
    url: '/common/meeting-room',
    method: 'post',
    data: {
      id: currentRoom.value.id,
      date: dayjs(selectedDate.value).format("YYYY-MM-DD HH:mm:ss.SSSZ")
    }
  })
  roomStatusString.value = response.data.records[0].status
}
const validateAttendees = (rule, value, callback) => {
  if (value > currentRoom.value.seatNum) {
    callback(new Error(`参会人数不能超过${currentRoom.value.name}的座位数 ${currentRoom.value.seatNum}`))
  } else {
    callback()
  }
}

const bookingRules = reactive({
  date: [{ required: true, message: '请选择预约日期', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  attendees: [{ required: true, message: '请输入参会人数', trigger: 'change' }]
})

const recommendDialogVisible = ref(false)
const timeRangeType = ref('custom')

const recommendForm = reactive({
  date: '',
  startTime: '',
  endTime: '',
  attendees: null,
  deviceIds: [],
  minPrice: null,
  maxPrice: null,
  type: null
})

const handleTimeRangeChange = (type) => {
  switch (type) {
    case 'allDay':
      recommendForm.startTime = '08:00'
      recommendForm.endTime = '21:00'
      break
    case 'morning':
      recommendForm.startTime = '08:00'
      recommendForm.endTime = '12:00'
      break
    case 'afternoon':
      recommendForm.startTime = '12:00'
      recommendForm.endTime = '18:00'
      break
    case 'evening':
      recommendForm.startTime = '18:00'
      recommendForm.endTime = '21:00'
      break
  }
}

const recommendRules = reactive({
  date: [{ required: true, message: '请选择预约日期', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  attendees: [{ required: true, message: '请输入参会人数', trigger: 'change' }]
})
const currentRoomDevices = ref([])

const searchForm = ref({
  name: '',
  type: '',
  status: ''
})

// 推荐信息相关的响应式变量
const showRecommendInfo = ref(false)
const recommendTimeRange = ref([])
const recommendAttendees = ref(null)
const recommendDevices = ref([])
const recommendMaxPrice = ref(null)
const recommendType = ref(null)

// 预加载的3D模型URL
const MODEL_URLS = {
  smallTable: 'https://prod.spline.design/qrpSRzdjgVtujLuM/scene.splinecode',
  bigTable: 'https://prod.spline.design/urL2Q0QNUcCsa6Z9/scene.splinecode',
  smallClass: 'https://prod.spline.design/CETIgHUmUyHn5xPb/scene.splinecode',
  bigClass: 'https://prod.spline.design/SkFwJPGPgHpfFbHc/scene.splinecode'
}

// 预加载的模型容器
const preloadedModels = ref({
  smallTable: null,
  bigTable: null,
  smallClass: null,
  bigClass: null
})

// 预加载3D模型
const preloadModels = () => {
  // 创建隐藏的容器来预加载模型
  const container = document.createElement('div')
  container.style.display = 'none'
  document.body.appendChild(container)

  // 预加载所有模型
  Object.entries(MODEL_URLS).forEach(([key, url]) => {
    const viewer = document.createElement('spline-viewer')
    viewer.setAttribute('url', url)
    viewer.style.width = '1px'
    viewer.style.height = '1px'
    container.appendChild(viewer)
    
    // 监听加载完成事件
    viewer.addEventListener('load', () => {
      preloadedModels.value[key] = viewer
    })
  })
}

// 获取预加载的模型
const getPreloadedModel = (type, seatNum) => {
  if (type === 1) { // 圆桌型
    return seatNum <= 6 ? preloadedModels.value.smallTable : preloadedModels.value.bigTable
  } else { // 教室型
    return seatNum <= 6 ? preloadedModels.value.smallClass : preloadedModels.value.bigClass
  }
}

// 格式化时间范围
const formatTimeRange = (timeRange) => {
  const start = `${timeRange.date} ${timeRange.startTime}`
  const end = `${timeRange.date} ${timeRange.endTime}`
  return `${start} 至 ${end}`
}

const getCurrentHourStatus = (status) => {
  const currentHour = new Date().getHours(); // 获取当前小时，范围 0~23
  return String(status).charAt(currentHour);
}

async function getRoomList() {
  try {
    const response = await request({
      url: '/common/meeting-room',
      method: 'post',
      data: {
        ...searchForm.value,
        date: new Date(),
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })
    roomList.value = response.data.records.map(room => {
      const currentHourStatus = getCurrentHourStatus(room.status)
      return {
        ...room,
        curStatus: parseInt(currentHourStatus)
      }
    })
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取会议室列表失败：' + error.message)
  }
}

// 获取设备列表
const getDeviceList = async () => {
  try {
    const response = await request.post('/admin/media-device-list', {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.value.name
    })
    if (response.code === 200) {
      devicesList.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取设备列表失败')
    }
  } catch (error) {
    ElMessage.error(error.message||'获取设备列表失败')
  }
}

const handleSearch = () => {
  getRoomList()
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    type: '',
    status: ''
  }
  showRecommendInfo.value = false
  handleSearch()
}

const handleRoomClick = (room) => {
  currentRoom.value = room
  roomDetailVisible.value = true
  selectedDate.value = dayjs().format('YYYY-MM-DD')
  fetchRoomStatus()
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '空闲';
    case 1: return '锁定';
    case 2: return '预定';
    case 3: return '使用';
    case 4: return '维护';
    default: return '';
  }
};

const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'success';
    case 1: return 'warning';
    case 2: return 'primary';
    case 3: return 'danger';
    case 4: return 'info';
    default: return '';
  }
};

const handleViewDevices = async (room) => {
  try {
    const response = await request({
      url: '/common/media',
      method: 'get',
      params: {
        meetingRoomId: room.id
      }
    })
    currentRoomDevices.value = response.data
    deviceDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取会议室设备列表失败：' + error.message)
  }
}

const handleBookRoom = async () => {
  bookingDialogVisible.value = true
}

const handleRecommend = () => {
  recommendDialogVisible.value = true
}

const recommendFormRef = ref(null)
const isRecommending = ref(false)

const submitRecommend = async () => {
  if (!recommendFormRef.value) return
  await recommendFormRef.value.validate().catch(err => {
    ElMessage.warning('请填写必要的推荐条件')
    throw err
  })
  isRecommending.value = true
      try {
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('推荐请求超时，请稍后重试')), 5000)
        })
        const startTime = dayjs.tz(`${recommendForm.date}T${recommendForm.startTime}:00`, 'YYYY-MM-DDTHH:mm:ss', 'Asia/Shanghai').format("YYYY-MM-DD HH:mm:ss.SSSZ")
        const endTime = dayjs.tz(`${recommendForm.date}T${recommendForm.endTime}:00`, 'YYYY-MM-DDTHH:mm:ss', 'Asia/Shanghai').format("YYYY-MM-DD HH:mm:ss.SSSZ")
        const requestPromise = request({
          url: '/customer/recommend-meeting-rooms',
          method: 'post',
          data: {
            startTime: startTime,
            endTime: endTime,
            attendees: recommendForm.attendees,
            deviceIds: recommendForm.deviceIds,
            maxPrice: recommendForm.maxPrice,
            roomType: recommendForm.type
          }
        })
        const response = await Promise.race([requestPromise, timeoutPromise])
      if(response.success) {
        roomList.value = response.data.records.sort((a, b) => a.price - b.price).map(room => {
          room.seatNum = room.seats
          room.price = room.pricePerHour
          return room
        })
        total.value = response.data.total
        recommendDialogVisible.value = false
        ElMessage.success("以下是系统根据您需求推荐的会议室")
        
        // 更新推荐信息展示
        showRecommendInfo.value = true
        recommendTimeRange.value.date = recommendForm.date
        recommendTimeRange.value.startTime = recommendForm.startTime
        recommendTimeRange.value.endTime = recommendForm.endTime
        recommendAttendees.value = recommendForm.attendees
        recommendDevices.value = currentRoomDevices.value
          .filter(device => recommendForm.deviceIds.includes(device.id))
          .map(device => device.name)
        recommendMaxPrice.value = recommendForm.maxPrice
        recommendType.value = recommendForm.type
      }
    } catch (error) {
      ElMessage.error('获取推荐会议室失败：' + error.message)
    } finally {
      isRecommending.value = false
    }
}

const payDialogVisible = ref(false)
const paymentMethod = ref(null)
const currentOrderId = ref(null)
const orderAmount = ref(0)
const paymentCountdown = ref(30 * 60) // 30分钟倒计时
const countdownTimer = ref(null)
const showQRCode = ref(false)
const isPaymentProcessing = ref(false)

const isSubmitting = ref(false)

const submitBooking = async () => {
  if (isSubmitting.value) return
  isSubmitting.value = true
  try {
    if (!bookingForm.date || !bookingForm.startTime || !bookingForm.endTime) {
      ElMessage.warning('请选择完整的预约时间')
      return
    }
    
    // 验证参会人数是否超过会议室座位数限制
    if (bookingForm.attendees > currentRoom.value.seatNum) {
      ElMessage.warning(`参会人数不能超过会议室座位数 ${currentRoom.value.seatNum} 人`)
      return
    }
    const startTime = dayjs.tz(`${bookingForm.date}T${bookingForm.startTime}:00`, 'YYYY-MM-DDTHH:mm:ss', 'Asia/Shanghai').format("YYYY-MM-DD HH:mm:ss.SSSZ")
    const endTime = dayjs.tz(`${bookingForm.date}T${bookingForm.endTime}:00`, 'YYYY-MM-DDTHH:mm:ss', 'Asia/Shanghai').format("YYYY-MM-DD HH:mm:ss.SSSZ")
    
    // 验证开始时间和结束时间
    if (dayjs(startTime).isAfter(dayjs(endTime))) {
      ElMessage.warning('开始时间不能晚于结束时间')
      return
    }
    if (dayjs(startTime).isSame(dayjs(endTime))) {
      ElMessage.warning('开始时间不能与结束时间相同')
      return
    }
    
    const response = await request({
      url: '/customer/create-order',
      method: 'post',
      data: {
        meetingRoomId: currentRoom.value.id,
        startTime: startTime,
        endTime: endTime,
        attendees: bookingForm.attendees,
      }
    })

    bookingDialogVisible.value = false
    if (response.success) {
      currentOrderId.value = response.data.id
      orderAmount.value = response.data.totalAmount
      payDialogVisible.value = true
      // 开始倒计时
      paymentCountdown.value = 30 * 60
      if (countdownTimer.value) clearInterval(countdownTimer.value)
      countdownTimer.value = setInterval(() => {
        if (paymentCountdown.value > 0) {
          paymentCountdown.value--
        } else {
          clearInterval(countdownTimer.value)
          payDialogVisible.value = false
          ElMessage.warning('支付超时')
        }
      }, 1000)
    }
  } catch (error) {
    ElMessage.error('创建订单失败：' + error.message)
  } finally {
    isSubmitting.value = false
  }
}

const formatCountdown = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

const handlePayNow = async () => {
  if (paymentMethod.value==null) {
    ElMessage.warning('请选择支付方式')
    return
  }
  showQRCode.value = true
}

const cancelPayment = () => {
  showQRCode.value = false
  roomDetailVisible.value = false
  paymentMethod.value = null
}

const confirmPayment = async () => {
  if (isPaymentProcessing.value) return
  
  isPaymentProcessing.value = true
  try {
    const response = await request({
      url: `/customer/pay-order`,
      method: 'post',
      data: {
        orderId: currentOrderId.value,
        paymentMethod: paymentMethod.value
      }
    })

    if (response.success) {
      ElMessage.success('支付成功')
      payDialogVisible.value = false
      roomDetailVisible.value = false
      if (countdownTimer.value) {
        clearInterval(countdownTimer.value)
      }
      getRoomList() // 刷新会议室列表
    } else {
      throw new Error(response.message || '支付失败')
    }
  } catch (error) {
    ElMessage.error('支付失败：' + error.message)
  } finally {
    isPaymentProcessing.value = false
  }
}
const handlePayLater = () => {
  payDialogVisible.value = false
  roomDetailVisible.value = false
  if (countdownTimer.value) clearInterval(countdownTimer.value)
  ElMessage.info('您可以稍后在订单管理中完成支付')
}

const getStatusClass = (status) => {
  switch (status) {
    case 0: return 'success';
    case 1: return 'warning';
    case 2: return 'primary';
    case 3: return 'danger';
    case 4: return 'info';
    default: return '';
  }
};

onMounted(() => {
  getRoomList()
  getDeviceList()
  preloadModels()
  
  let colorbg = new BlurGradientBg({ 
    dom: "box", 
    colors: ["#cce5ff","#c2c9f0","#8d8fad","#3d6492"], 
    loop: true 
  })
})
</script>

<style scoped>
@font-face {
  font-family: "汉仪雅酷黑-85";
  src: url("../../assets/fonts/汉仪雅酷黑-85.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}

.room-page-wrapper {
  display: flex;
  justify-content: center;
}

.room-status-container {
  width: 88%;
    max-width: 1700px;
    background: transparent;
    border-radius: 12px;
    position: relative; 
}

.search-bar {
  margin-bottom: -220px;
  padding: 40px 24px 230px 24px;
  border-radius: 36px;
  box-shadow: 0 2px 12px rgba(61, 100, 146, 0.15);
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #3d6492 0%, #abcdee 100%);
}

.search-title {
  margin-top: 0;
  margin-bottom: 8px;
  color: #ffffff;
  position: relative;
  z-index: 10;
  font-family: "汉仪雅酷黑-85", sans-serif;
  font-size: 36px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-guide {
  margin-top: 0;
  margin-bottom: 16px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  position: relative;
  z-index: 10;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: flex-end;
  position: relative;
  z-index: 10;
  justify-content: center;
}

.form-group {
  display: flex;
  flex-direction: row;
  gap: 8px;
  align-items: center;
}

.form-group label {
  color: #ffffff;
  font-size: 14px;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.custom-input {
  min-width: 200px;
  padding: 8px 12px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.15);
  color: #fff;
  font-size: 14px;
  transition: all 0.3s ease;
  backdrop-filter: blur(4px);
}

.custom-input:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.5);
  background: rgba(255, 255, 255, 0.2);
  box-shadow: 0 0 0 3px rgba(171, 205, 238, 0.3);
}

.custom-input::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.custom-select {
  min-width: 120px;
  padding: 8px 12px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.15);
  color: #fff;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23ffffff' d='M6 8.825L1.175 4 2.238 2.938 6 6.7 9.763 2.937 10.825 4z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 12px center;
  padding-right: 32px;
  backdrop-filter: blur(4px);
}

.custom-select:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.5);
  background-color: rgba(255, 255, 255, 0.2);
  box-shadow: 0 0 0 3px rgba(171, 205, 238, 0.3);
}

.custom-select option {
  background: #3d6492;
  color: #fff;
}

.form-actions {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 8px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.btn:focus {
  outline: none;
}

.btn::after {
  content: '';
  position: absolute;
  inset: 0;
  border: 2px solid transparent;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn:focus::after {
  border-color: rgba(255, 255, 255, 0.4);
}

.btn-primary {
  background: #3d6492;
  color: #fff;
  box-shadow: 0 2px 8px rgba(61, 100, 146, 0.3);
}

.btn-primary:hover {
  background: #2d4f7a;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(61, 100, 146, 0.4);
}

.btn-primary:active {
  transform: translateY(1px);
  box-shadow: 0 1px 4px rgba(61, 100, 146, 0.3);
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.15);
  color: #fff;
  border: 2px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 2px 8px rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(4px);
}

.btn-secondary:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
  border-color: rgba(255, 255, 255, 0.4);
  box-shadow: 0 4px 12px rgba(255, 255, 255, 0.15);
}

.btn-secondary:active {
  transform: translateY(1px);
  background: rgba(255, 255, 255, 0.1);
  box-shadow: 0 1px 4px rgba(255, 255, 255, 0.1);
}

.room-grid-container {
  margin-bottom: 24px;
}

.room-grid {
display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 50px;
    margin-bottom: 24px;
    position: relative;
    z-index: 10;
    padding: 20px 50px;
}

.room-card {
  background: #fff;
  border-radius: 24px;
  padding: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  cursor: pointer;
  transition: all 0.5s ease;
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;
  position: relative;
  overflow: visible;
}

/* 小教室 */
.room-card:has(img.room-decoration-ClassRoom-Regular) {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 60%), #fff;
}

/* 大教室 */
.room-card:has(img.room-decoration-ClassRoom) {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 60%), #fff;
}

/* 小圆桌 */
.room-card:has(img.room-decoration-TableRoom-Regular) {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 60%), #fff;
}

/* 大圆桌 - 深紫色渐变 */
.room-card:has(img.room-decoration-TableRoom) {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 60%), #fff;
}

/* 悬停效果增强 */
.room-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
}

.room-card:has(img.room-decoration-ClassRoom-Regular):hover {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 70%), #fff;
}

.room-card:has(img.room-decoration-ClassRoom):hover {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.38) 0%, #fff 70%), #fff;
}

.room-card:has(img.room-decoration-TableRoom-Regular):hover {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.38) 0%, #fff 70%), #fff;
}

.room-card:has(img.room-decoration-TableRoom):hover {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.38) 0%, #fff 70%), #fff;
}

.room-decoration-TableRoom-Regular {
  position: absolute;
  bottom: -8%;
  right: -7%;
  width: 110%;
  height: 110%;
  object-fit: contain;
  pointer-events: none;
  z-index: 1;
  opacity: 1;
  transition: all 0.3s ease;
}

.room-card:hover .room-decoration-TableRoom-Regular {
  transform: scale(1.1);
  opacity: 1;
}

.room-decoration-TableRoom {
  position: absolute;
  bottom: -18%;
  right: -19%;
  width: 130%;
  height: 130%;
  object-fit: contain;
  pointer-events: none;
  z-index: 1;
  opacity: 1;
  transition: all 0.3s ease;
}

.room-card:hover .room-decoration-TableRoom {
  transform: scale(1.1);
  opacity: 1;
}

.room-decoration-ClassRoom-Regular  {
  position: absolute;
  bottom: -6%;
  right: -5%;
  width: 110%;
  height: 110%;
  object-fit: contain;
  pointer-events: none;
  z-index: 1;
  opacity: 1;
  transition: all 0.3s ease;
}

.room-card:hover .room-decoration-ClassRoom-Regular {
  transform: scale(1.1);
  opacity: 1;
}

.room-decoration-ClassRoom {
  position: absolute;
  bottom: -16%;
  right: -16%;
  width: 130%;
  height: 130%;
  object-fit: contain;
  pointer-events: none;
  z-index: 1;
  opacity: 1;
  transition: all 0.3s ease;
}

.room-card:hover .room-decoration-ClassRoom {
  transform: scale(1.1);
  opacity: 1;
}

.room-card-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.room-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.room-card-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.room-card-price .price-amount {
  font-size: 24px;
  font-weight: 600;
  color: #f56c6c;
}

.room-card-price .price-unit {
  font-size: 14px;
  color: #909399;
}

.room-card-type {
  font-size: 14px;
  color: #999;
  margin-top: auto;
}

.room-detail {
  padding: 0 20px;
}

.detail-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}


.detail-item .el-input__inner{
  text-align: center;
}


.detail-item .label {
  text-align: left;
  color: #666;
  font-size: 16px;
  width: 100px;
  flex: 1; 
}

.time-status-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  margin-bottom: 12px;
}

.time-status-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.time-label {
  font-size: 11px;
  color: #666;
  padding: 3px 6px;
  border-radius: 3px;
  text-align: center;
  width: 100%;
}

.time-label.success {
  background-color: #67c23a;
  color: #fff;
}

.time-label.warning {
  background-color: #e6a23c;
  color: #fff;
}

.time-label.primary {
  background-color: #409eff;
  color: #fff;
}

.time-label.danger {
  background-color: #f56c6c;
  color: #fff;
}

.time-label.info {
  background-color: #909399;
  color: #fff;
}

.status-legend {
  margin-top: 12px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 6px;
}

.legend-title {
  font-size: 12px;
  color: #606266;
  margin-bottom: 6px;
}

.legend-items {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  flex-shrink: 0;
}

.legend-text {
  font-size: 11px;
  color: #606266;
}

.recommend-info {
  display: flex;
  align-items: center;
  justify-content: center;
}

.recommend-criteria {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.recommend-criteria span {
  color: #606266;
  font-size: 14px;
}

/* 会议室详情对话框样式 */
.room-detail-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.dialog-content {
  background: #fff;
  border-radius: 24px;
  width: 60%;

  max-width: 1200px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  animation: dialogFadeIn 0.3s ease;
}

@keyframes dialogFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.dialog-header {
  padding: 12px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  background: #ffffff;
}

.dialog-header h2 {
  margin: 0;
  color: #476490;
  font-size: 18px;
  font-weight: 600;
  font-family: "汉仪雅酷黑-85", sans-serif;
}

.close-btn {
  border: none;
  background: transparent;
  padding: 6px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.close-btn:active {
  background: rgba(0, 0, 0, 0.1);
}

.dialog-body {
  display: flex;
  min-height: 500px;
}

.room-image-container {
  flex: 1;
  padding: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f8f9fa;
  border-right: 1px solid rgba(0, 0, 0, 0.1);
  width: 50%;
  position: relative;
}

.room-detail-model {
  width: 100%;
  height: 100%;
  min-height: 500px;
  position: absolute;
  top: 0;
  left: 0;
}

.room-detail-model spline-viewer {
  width: 100%;
  height: 100%;
}

.room-detail {
  flex: 0.8;
  padding: 24px;
  background: rgba(255, 255, 255, 0.95);
  overflow-y: auto;
}

.detail-item .value {
  color: #333;
    font-size: 16px;
    font-weight: 480;
}

.detail-item .value.price {
  color: #f56c6c;
  font-weight: 600;
}

.status-tag {
  padding: 2px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  color: #fff;
}

.status-tag.small {
  padding: 2px 8px;
  font-size: 12px;
}

.status-tag.success {
  background: #67c23a;
}

.status-tag.warning {
  background: #e6a23c;
}

.status-tag.primary {
  background: #409eff;
}

.status-tag.danger {
  background: #f56c6c;
}

.status-tag.info {
  background: #909399;
}

.time-status-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-top: 16px;
}

.time-status-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.time-label {
  font-size: 8px;
  color: #666;
}

.detail-actions {
  padding: 20px 24px;
  display: flex;
  justify-content: center;
  gap: 16px;
  background: rgba(255, 255, 255, 0.95);
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.action-btn {
  padding: 8px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn.view-devices {
  background: #3d6492;
  color: #fff;
}

.action-btn.book-room {
  background: #67c23a;
  color: #fff;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-btn:active {
  transform: translateY(1px);
}

.loading-spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  z-index: 0;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3d6492;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: #3d6492;
  font-size: 14px;
  font-weight: 500;
}

.criteria-item {
  display: inline-block;
  padding: 4px 8px;
  background-color: rgba(64, 158, 255, 0.1);
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>